﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;

using System.Data.Services.Client;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using CPlase.Internal;

namespace CPlase
{
    public static class Queue
    {

        #region Service
        private static CloudQueueClient queueStorage;

        private static List<string> s_createdQueue = new List<string>();
        private static object s_lock = new Object();

        private static void CreateOnceQueue(string QueueName)
        {

            if (s_createdQueue.Exists(new Predicate<string>(s => s == QueueName)))
                return;

            lock (s_lock)
            {

                if (s_createdQueue.Exists(new Predicate<string>(s => s == QueueName)))
                    return;

                try
                {

                    CloudStorageAccount account = Azure.GetStorageAccount();

                    queueStorage = account.CreateCloudQueueClient();
                    CloudQueue queue = queueStorage.GetQueueReference(QueueName);

                    queue.CreateIfNotExist();
                }
                catch (WebException)
                {
                    // display a nice error message if the local development storage tool is not running or if there is 
                    // an error in the account configuration that causes this exception
                    throw new WebException("The Windows Azure storage services cannot be contacted " +
                         "via the current account configuration or the local development storage tool is not running. " +
                         "Please start the development storage tool if you run the service locally!");
                }
                s_createdQueue.Add(QueueName);
            }
        }
        #endregion

        public static CloudQueue GetQueue(string QueueName)
        {
            CreateOnceQueue(QueueName);
            return queueStorage.GetQueueReference(QueueName);
        }

        public static bool AddToQueue<QueueHandlerType>(string Task) where QueueHandlerType : IWorkerQueueHandler
        {
            var Queue = GetQueue(WorkerQueueHandlerExtensions.GetQueueName(typeof(QueueHandlerType)));
            return AddToQueue<QueueHandlerType>(Queue, Task);
        }

        public static bool AddToQueue<QueueHandlerType>(CloudQueue Queue, string Task)
        {
            try
            {
                var Message = new CloudQueueMessage(Task);
                Queue.AddMessage(Message);
                Internal.RoleCommunicatior.WorkerRoleCommand(typeof(QueueHandlerType));
                return true;
            }
            catch { return false; }
        }




    }
}